import React from 'react';
import {
  Form,
  Modal,
  Card,
  DatePicker,
  Input,
  InputNumber,
  Radio,
  Button,
  Table,
  Row,
  Col
} from 'antd';
import { LwjUpload,LwjDownload} from 'components';
import { validateMobile } from 'utils/utils';

const FormItem = Form.Item
const RadioGroup = Radio.Group
const formItemLayout = {
  labelCol: {
    span: 6
  },
  wrapperCol: {
    span: 14
  }
}
const customPanelStyle = {
  marginBottom: 24
};
const PublishEndOrderModal = ({
  dispatch,
  toChangeOrder,
  onOk,
  onAddMaterielItem,
  isUpdate,
  isLoading,
  currentContractDetail,
  onDeleteMaterielItem,
  onMaterielItemChange,
  isPushOmsModel,
  form: {
    getFieldDecorator,
    validateFieldsAndScroll
  },
  ...updateModalProps
}) => {
  const handleSubmit = (handleType) => {
    if (handleType === "ORDER_CHANGE") {
      toChangeOrder();
      return;
    }
    validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (handleType === "CONFIRM_SUBMIT" && isPushOmsModel) {
          values.contractSignedAt = values.contractSignedAt.valueOf();
          values.contractInstalledAt = values.contractInstalledAt.valueOf();
          _.each(currentContractDetail.materielItems, (item) => {
            delete item.index;
          });
          values.materielItems = currentContractDetail.materielItems;
          values.productType = currentContractDetail.productType;
          values.version = currentContractDetail.version;
          delete values.quoteAttachment;
          if (!values.materielItems.every((item, index, array) => {
            return item.code !== "" && item.quantity !== "" && item.name !== ""
          })) {
            Modal.error({
              title: '错误',
              content: '请填写所有的物料编码、物料名称以及数量',
            });
            return;
          }
          onOk(values);
        } else {
          dispatch({
            type: "updateContractOrder/toTenant",
            payload: {
              isPushOms: isPushOmsModel,
            }
          })
          dispatch({
            type: 'updateContractOrder/hidePublishEndOrderModal',
            payload: {}
          });
        }
      }
    });
  };

  const xlsProps = {
    maxfile:1,
    target: '/services/upload/order',
    uploadIcon: 'upload',
    accept:'image/*,.pdf,.dwg,.dwf,.zip,.rar,.xlsx,.xls',
    fileType: '',
    onChange(value) {
    },
    showUploadList: true
  }

  const renderColumns = (text, record, column) => {
    return (
      <div>
        {currentContractDetail.isFromThirdPart? text:
        <Input
          style={{ margin: '-5px 0' }}
          value={text}
          onChange={e => onMaterielItemChange(e.target.value, record, column)} />}
      </div>);
  }

  const paramsColumns = [
    {
      title: '物料编号',
      dataIndex: 'code',
      key: 'code',
      render: (text, record) => (<span>{text}</span>)
    }, {
      title: '物料名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (<span>{text}</span>)
    }, {
      title: '物料数量',
      dataIndex: 'quantity',
      key: 'quantity',
      render: (text, record) => renderColumns(text, record, 'quantity')
    }, {
      title: '操作',
      render: (text, record) => {
        return (
           <div>
            <a onClick={() => onDeleteMaterielItem(record)}>删除</a>
          </div>
        );
      },
    }
  ];

  const listProps = {
    dataSource: currentContractDetail.materielItems,
    pagination: false
  }

  const getParamsColumns = (option) => {
      if(option) {
        paramsColumns.pop();
      }
      return  paramsColumns;
  }

  const isNeedPush = (option) => {
    dispatch({
      type: "updateContractOrder/isPushOms",
      payload: {
        isPushOms: option,
      }
    })
  }
  return (
    <Modal {...updateModalProps}>
      <Form onSubmit={handleSubmit} hideRequiredMark>
        {(!_.isEmpty(currentContractDetail) && currentContractDetail.status === "PENDING_PUBLISH") &&
          <Card type="inner" title="下单信息" style={customPanelStyle}>
            <Row>
              <Col span={12}>
                <FormItem {...formItemLayout} label="合同号">
                  {getFieldDecorator('contractNum', {
                    rules: [
                      {
                        required: true,
                        message: '请输入合同号',
                        whitespace: true
                      },
                    ],
                    initialValue: currentContractDetail.contractNum
                  })(<Input disabled placeholder="请输入合同号" />)}
                </FormItem>
                <FormItem {...formItemLayout} label="合同签订时间">
                  {getFieldDecorator('contractSignedAt', {
                    rules: [
                      {
                        required: true,
                        message: '请选择合同下单时间',
                        type: 'object',
                      },
                    ],
                    initialValue: currentContractDetail.orderContractAt
                  })(
                    <DatePicker  style={{ width: '100%' }} />
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="合同到货时间">
                  {getFieldDecorator('contractInstalledAt', {
                    rules: [
                      {
                        required: true,
                        message: '请选择合同到货时间',
                        type: 'object',
                      },
                    ],
                    initialValue: currentContractDetail.installContractAt
                  })(
                    <DatePicker  style={{ width: '100%' }} />
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="合同金额">
                  {getFieldDecorator('contractAmount', {
                    rules: [
                      {
                        required: true,
                        message: '请输入合同金额'
                      },
                    ],
                    initialValue: currentContractDetail.orderQuoteSummary.orderAmount
                  })(<InputNumber disabled style={{ width: "100%" }} placeholder="请输入合同金额" />)}
                </FormItem>
                <FormItem {...formItemLayout} label="收货人姓名">
                  {getFieldDecorator('receiptUserName', {
                    rules: [
                      {
                        required: true,
                        message: '请输入收货人姓名',
                        whitespace: true,
                      },
                    ],
                    initialValue: currentContractDetail.receiptUserName
                  })(<Input disabled placeholder="请输入收货人姓名" />)}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem {...formItemLayout} label="收货人手机号">
                  {getFieldDecorator('receiptUserPhoneNum', {
                    rules: [
                      {
                        required: true,
                        message: '请输入收货人手机号',
                        whitespace: true
                      }, {
                        validator: validateMobile
                      }
                    ],
                    initialValue: currentContractDetail.receiptUserPhoneNum
                  })(<Input disabled placeholder="请输入收货人手机号" />)}
                </FormItem>
                <FormItem {...formItemLayout} label="收货地址">
                  {getFieldDecorator('receiptAddress', {
                    rules: [
                      {
                        required: true,
                        message: '请输入收货地址',
                        whitespace: true
                      },
                    ],
                    initialValue: currentContractDetail.receiptAddress
                  })(<Input disabled placeholder="请输入收货地址" />)}
                </FormItem>
                {isPushOmsModel && <FormItem {...formItemLayout} label="报价方案">
                  {getFieldDecorator('quoteAttachment', {
                    initialValue: currentContractDetail.orderQuoteSummary.quoteAttachment
                  })(<LwjDownload title={'点击下载'} targetUrl={currentContractDetail.orderQuoteSummary.quoteAttachment} />)}
                </FormItem>}
                {isPushOmsModel && <FormItem {...formItemLayout} label="备注">
                  {getFieldDecorator('memo', {
                    initialValue: currentContractDetail.memo
                  })(<Input placeholder="请输入备注" />)}
                </FormItem>}
                {currentContractDetail.pushToOMSNeeded === null && <FormItem {...formItemLayout} label="下单选项">
                  {getFieldDecorator('isPushOms', {
                    rules: [
                      {
                        required: true,
                        message: '请选择是否推送'
                      }
                    ],
                    initialValue: "true"
                  })(
                    <RadioGroup>
                      <Radio value="true" onClick={() => isNeedPush(true)}>成品下单到丽维家</Radio>
                      <Radio value="false" onClick={() => isNeedPush(false)}>成品下单到租客</Radio>
                    </RadioGroup>
                  )}
                </FormItem>}
              </Col>
            </Row>
          </Card>}
        {isPushOmsModel && <Card type="inner" title="成品列表" style={customPanelStyle} >
          {!currentContractDetail.isFromThirdPart && <Button onClick={e => onAddMaterielItem()} style={{ marginBottom: 10 }} >添加物料</Button>}
          <Table
            columns={getParamsColumns(currentContractDetail.isFromThirdPart)}
            size="middle"
            rowKey={record => record.code}
            {...listProps} />
        </Card>}
        <FormItem
          style={{ marginTop: 30 }}
          wrapperCol={{ span: 6, offset: 19 }}>
          <Button onClick={() => handleSubmit("ORDER_CHANGE")} style={{ marginRight: 10 }}>
            合同变更
          </Button>
          <Button type="primary" onClick={() => handleSubmit("CONFIRM_SUBMIT")} style={{ marginRight: 10 }} loading={isLoading}>
            确认下单
          </Button>
        </FormItem>
      </Form>
    </Modal>
  )
}

export default Form.create()(PublishEndOrderModal);
